package com.learn.hmspring.dao.impl;

import com.learn.hmspring.dao.AccountDao;
import com.learn.hmspring.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

@Repository
public class AccountDaoImpl implements AccountDao {

    @Autowired
    public QueryRunner qr;

    public Account ac;

    public List<Account> lac;


    public void saveAccount(Account account) {
        try {
            qr.update("insert into apply.account values(?,?,?)",account.getId(),account.getName(),account.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public Account findAccountById(Integer id) {
        try {
            ac = qr.query("select * from apply.account where id=?", new BeanHandler<Account>(Account.class), id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ac;
    }

    public void updateAccount(Account account) {
        try {
            qr.update("update apply.account set id=?,name=?,money=?", account.getId(), account.getName(), account.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void deleteAccount(Account account) {
        try {
            qr.update("delete apply.account where id=?",account.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public List<Account> findAllAccount() {
        try {
            lac = qr.query("select * from apply.account", new BeanListHandler<Account>(Account.class));

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return lac;

    }
}
